/*********************************************************************
 * PhSprite. Clase de utilidad. Sprite con propiedades Físicas.
 * Programación Multimedia y Juegos
 * Autor: David Vallejo Fernández    david.vallejo@tegnix.com
 * Autor: Carlos González Morcillo   carlos.gonzalez@tegnix.com
 *
 * You can redistribute and/or modify this file under the terms of the
 * GNU General Public License ad published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * and later version. See <http://www.gnu.org/licenses/>.
 *
 * This file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.  
 *********************************************************************/

package physic;

import aze.display.TileSprite;
import aze.display.TileLayer;

import phx.World;
import phx.Body;
import phx.Shape;

class PhSprite extends TileSprite {
  var _root:TileLayer;     // Capa de dibujado del objeto
  var _world:World;        // Mundo de simulación en Physaxe
  var _body:Body;          // Cuerpo físico de simulación
  var _isDynamic:Bool;     // El objeto es dinámico o estático?

  // Este método debe ser sobreescrito...
  // Si es una StaticShape, puede añadirlas al mundo y devolver null
  function createShape():Shape {
    return null;
  }

  // Constructor ==================================================
  public function new(id:String, l:TileLayer, w:World, px:Float, 
	         py:Float, isDynamic:Bool, ?vect:phx.Vector):Void {
    super(id); _root = l; _world = w; _isDynamic = isDynamic;
    x = px; y = py; 
    _root.addChild(this);
    if (_isDynamic) {
      _body = new Body(x,y);
      _body.addShape(createShape());
      _body.w = Std.random(100)/1000.0;   // Veloc. Angular
      _body.v = vect;
      _body.updatePhysics();
      _world.addBody(_body);
    }
    else {  
      // El objeto es estático, puede añadir la forma al mundo 
      //   en el propio método "createShape"
      var s = createShape();   
      if (s!=null) _world.addStaticShape(s);
    }
  }

  // Destructor ===================================================
  public function destroy():Void {
    if (_isDynamic) _world.removeBody(_body);
    _root.removeChild(this);    
  }

  // Update =======================================================
  public function update(w:Int, h:Int):Bool {
    if (_isDynamic) {
      x = _body.x;
      y = _body.y;
      rotation = _body.a;
      _body.updatePhysics();
    }
    return true;
  }
}